import { _decorator, Component, Node, EditBox, instantiate, Label, ScrollView, tween } from "cc";
const { ccclass, property } = _decorator;
import websocket from "./websocket";
import dwebAjax from "./dwebXHR";
/**
 * Predefined variables
 * Name = chatBox
 * DateTime = Sun Feb 27 2022 20:55:22 GMT+0800 (中国标准时间)
 * Author = 412845222
 * FileBasename = chatBox.ts
 * FileBasenameNoExtension = chatBox
 * URL = db://assets/script/chatBox.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 *
 */

@ccclass("chatBox")
export class chatBox extends Component {
  // [1]
  // dummy = '';

  // [2]
  // @property
  // serializableDummy = 0;
  userinfo = null;
  static ws: WebSocket = null;
  msg_item = null;
  text_content = null;
  otherModel = null;
  playerList = [];

  start() {
    this.otherModel = this.node.getParent().getParent().getChildByName("other");
    // [3]
    this.msg_item = this.node.getChildByPath("ScrollView/view/content/item");
    this.text_content = this.node.getChildByPath("ScrollView/view/content");

    let token = localStorage.getItem("token");
    console.log(token);
    let data = {
      token: token,
    };

    dwebAjax.sendAjax("/api-json/userinfo/", data, "POST", (res) => {
      console.log(res);
      this.userinfo = res;
      chatBox.ws = websocket.initWebSocket(this.userinfo.id + "/", this.onOpen, this.onMessage, this.onClose, this.onError);
    });
  }

  editingReturn(editBox: EditBox) {
    // [4]
    console.log(editBox);
    let str = editBox.string;
    console.log(str);
    let msg = {
      code: 200,
      message: {
        token: localStorage.getItem("token"),
        data: {
          text: str,
        },
      },
    };
    this.sendMessage(msg);
    editBox.string = "";
  }

  sendMessage(msg: object) {
    let text_data = JSON.stringify(msg);
    chatBox.ws.send(text_data);
  }

  onOpen = (e: any) => {
    console.log(e);
    let msg = {
      code: 100,
      message: {
        token: localStorage.getItem("token"),
        data: {
          text: "进入房间成功",
        },
      },
    };
    this.sendMessage(msg);
  };
  onMessage = (e: any) => {
    // console.log(e);
    let message = JSON.parse(e.data).message;
    if (message.code == 100 || message.code == 200) {
      // console.log(message);
      let new_msgItem = instantiate(this.msg_item);
      new_msgItem.getComponent(Label).string = message.nickName + "：" + message.data.text;
      this.text_content.addChild(new_msgItem);
    }
    if (message.code == 300 || message.code == 301 || message.code == 302) {
      // console.log(message);
      let other_id = message.id;
      let other_pos = message.data.pos;
      let new_player = null;
      let player_name = "other_" + other_id;
      if (other_id != this.userinfo.id) {
        if (this.playerList.indexOf(player_name) == -1) {
          this.playerList.push(player_name);
          new_player = instantiate(this.otherModel);
          new_player.name = player_name;
          this.node.getParent().getParent().addChild(new_player);
        } else {
          new_player = this.node.getParent().getParent().getChildByName(player_name);
          //各操作逻辑
          if (message.code == 300) {
            let keycode= parseInt(message.data.keycode);
            new_player.setPosition(other_pos);
            //87 83 65 68
            if (keycode==87) {
              new_player.getComponent("other").keydown_w = true
            }
            if (keycode==83) {
              new_player.getComponent("other").keydown_s = true
            }
            if (keycode==65) {
              new_player.getComponent("other").keydown_a = true
            }
            if (keycode==68) {
              new_player.getComponent("other").keydown_d = true
            }
            
          }
          if (message.code == 301) {
            let keycode= parseInt(message.data.keycode);
            new_player.setPosition(other_pos);
            //87 83 65 68
            if (keycode==87) {
              new_player.getComponent("other").keydown_w = false
            }
            if (keycode==83) {
              new_player.getComponent("other").keydown_s = false
            }
            if (keycode==65) {
              new_player.getComponent("other").keydown_a = false
            }
            if (keycode==68) {
              new_player.getComponent("other").keydown_d = false
            }
          }
          if (message.code == 302) {
            let rotation = message.data.rotation
            new_player.setRotationFromEuler(rotation)
          }
        }
      }
    }
  };
  onClose(e: any) {
    console.log(e);
  }
  onError(e: any) {
    console.log(e);
  }

  // update (deltaTime: number) {
  //     // [4]
  // }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.4/manual/zh/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.4/manual/zh/scripting/decorator.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.4/manual/zh/scripting/life-cycle-callbacks.html
 */
